<template>
  <div class="box">
    <!-- 头部 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>校园动态</span>
        <el-button style="float: right; padding: 3px 0" type="text"></el-button>
      </div>
      <div class="nav">
        <el-input
          v-model="params.idortitle"
          placeholder="请输入要搜索的内容"
        ></el-input>
        <!-- 查询 -->
        <el-button class="btn" @click="getnewlist()">查询</el-button>
        <!-- </template > -->
      </div>
    </el-card>
    <!-- 添加 删除 -->
    <div class="banner">
      <el-button type="primary" @click="att">添加</el-button>
      <el-button type="danger" @click="deleteall">批量删除</el-button>
    </div>
    <!-- 内容 -->
    <el-table
      border
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%; margin-top: 20px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50"> </el-table-column>
      <!-- <el-table-column label="ID" width="120" prop="news_id"> </el-table-column> -->
      <el-table-column prop="title" label="标题" width="250"> </el-table-column>
      <!-- <el-table-column prop="content" label="正文" show-overflow-tooltip>
      </el-table-column> -->
      <el-table-column prop="desc" label="介绍" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="thumb" label="图片" show-overflow-tooltip>
        <template #default="scope">
          <el-image
            :src="scope.row.thumb"
            alt=""
            style="width: 100px; height: 50px"
            :preview-src-list="[scope.row.thumb]"
            @error="imgError"
          />
        </template>
        <!-- <img src="../images/news.jpg" alt="" srcset="" style="width: 200px; height: 100px"> -->
      </el-table-column>
      <el-table-column prop="author" label="作者" show-overflow-tooltip>
      </el-table-column>
      <!-- <el-table-column
        prop="keywords"
        label="关键字"
        width="120"
        show-overflow-tooltip
      >
      </el-table-column> -->
      <!-- 按钮 -->
      <el-table-column label="操作" show-overflow-tooltip>
        <template slot-scope="scope"
          ><el-button
            type="success"
            @click="xiangq(scope.row.news_id)"
            size="mini"
            >详情</el-button
          >
          <el-button
            type="primary"
            @click="xiugai(scope.row, scope.row.news_id)"
            size="mini"
            >修改</el-button
          >
          <el-button
            type="danger"
            @click="getdele(scope.row.news_id)"
            size="mini"
            >删除</el-button
          >
        </template></el-table-column
      >
    </el-table>
    <!-- 分页 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.page"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 添加数据 -->
    <el-dialog title="添加" :visible.sync="dialogFormVisible" width="80%">
      <el-form :model="form" class="nanner">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="正文" :label-width="formLabelWidth">
          <div>
            <el-card style="height: 610px; width: 700px">
              <quill-editor
                v-model="form.content"
                ref="myQuillEditor"
                style="height: 500px"
                :options="editorOption"
              >
                <!-- 自定义toolar -->
                <div id="toolbar" slot="toolbar">
                  <!-- Add a bold button -->
                  <button class="ql-bold" title="加粗">Bold</button>
                  <button class="ql-italic" title="斜体">Italic</button>
                  <button class="ql-underline" title="下划线">underline</button>
                  <button class="ql-strike" title="删除线">strike</button>
                  <button class="ql-blockquote" title="引用"></button>
                  <button class="ql-code-block" title="代码"></button>
                  <button class="ql-header" value="1" title="标题1"></button>
                  <button class="ql-header" value="2" title="标题2"></button>
                  <!--Add list -->
                  <button
                    class="ql-list"
                    value="ordered"
                    title="有序列表"
                  ></button>
                  <button
                    class="ql-list"
                    value="bullet"
                    title="无序列表"
                  ></button>
                  <!-- Add font size dropdown -->
                  <select class="ql-header" title="段落格式">
                    <option selected>段落</option>
                    <option value="1">标题1</option>
                    <option value="2">标题2</option>
                    <option value="3">标题3</option>
                    <option value="4">标题4</option>
                    <option value="5">标题5</option>
                    <option value="6">标题6</option>
                  </select>
                  <select class="ql-size" title="字体大小">
                    <option value="10px">10px</option>
                    <option value="12px">12px</option>
                    <option value="14px">14px</option>
                    <option value="16px" selected>16px</option>
                    <option value="18px">18px</option>
                    <option value="20px">20px</option>
                  </select>
                  <select class="ql-font" title="字体">
                    <option value="SimSun">宋体</option>
                    <option value="SimHei">黑体</option>
                    <option value="Microsoft-YaHei">微软雅黑</option>
                    <option value="KaiTi">楷体</option>
                    <option value="FangSong">仿宋</option>
                    <option value="Arial">Arial</option>
                  </select>
                  <!-- Add subscript and superscript buttons -->
                  <select
                    class="ql-color"
                    value="color"
                    title="字体颜色"
                  ></select>
                  <select
                    class="ql-background"
                    value="background"
                    title="背景颜色"
                  ></select>
                  <select class="ql-align" value="align" title="对齐"></select>
                  <button class="ql-clean" title="还原"></button>
                  <!-- You can also add your own -->
                </div>
              </quill-editor>
            </el-card>
          </div>
        </el-form-item>
        <el-form-item label="关键字" :label-width="formLabelWidth">
          <el-input v-model="form.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="缩略图" :label-width="formLabelWidth">
          <!-- <el-input v-model="form.thumb" autocomplete="off"></el-input> -->
          <el-upload
            action="http://121.42.230.80/api/visit/upload"
            list-type="picture-card"
            :headers="headers"
            :show-file-list="false"
            :on-success="chec"
            :auto-upload="true"
          >
            <img
              v-if="thumb"
              :src="thumb"
              class="avatar"
              style="width: 145px; height: 145px"
            />
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
              style="margin-top: -20px; margin-left: -20px"
            ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth">
          <el-input v-model="form.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="form.desc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="add(form)">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 修改数据 -->
    <el-dialog title="修改" :visible.sync="xiug">
      <el-form :model="xiugaiform" class="nanner">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="xiugaiform.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="正文" :label-width="formLabelWidth">
          <!-- <el-input v-model="xiugaiform.content" autocomplete="off"></el-input> -->
          <div>
            <el-card style="height: 610px; width: 700px">
              <quill-editor
                v-model="xiugaiform.content"
                ref="myQuillEditor"
                style="height: 500px"
                :options="editorOption"
              >
                <!-- 自定义toolar -->
                <div id="toolbar" slot="toolbar">
                  <!-- Add a bold button -->
                  <button class="ql-bold" title="加粗">Bold</button>
                  <button class="ql-italic" title="斜体">Italic</button>
                  <button class="ql-underline" title="下划线">underline</button>
                  <button class="ql-strike" title="删除线">strike</button>
                  <button class="ql-blockquote" title="引用"></button>
                  <button class="ql-code-block" title="代码"></button>
                  <button class="ql-header" value="1" title="标题1"></button>
                  <button class="ql-header" value="2" title="标题2"></button>
                  <!--Add list -->
                  <button
                    class="ql-list"
                    value="ordered"
                    title="有序列表"
                  ></button>
                  <button
                    class="ql-list"
                    value="bullet"
                    title="无序列表"
                  ></button>
                  <!-- Add font size dropdown -->
                  <select class="ql-header" title="段落格式">
                    <option selected>段落</option>
                    <option value="1">标题1</option>
                    <option value="2">标题2</option>
                    <option value="3">标题3</option>
                    <option value="4">标题4</option>
                    <option value="5">标题5</option>
                    <option value="6">标题6</option>
                  </select>
                  <select class="ql-size" title="字体大小">
                    <option value="10px">10px</option>
                    <option value="12px">12px</option>
                    <option value="14px">14px</option>
                    <option value="16px" selected>16px</option>
                    <option value="18px">18px</option>
                    <option value="20px">20px</option>
                  </select>
                  <select class="ql-font" title="字体">
                    <option value="SimSun">宋体</option>
                    <option value="SimHei">黑体</option>
                    <option value="Microsoft-YaHei">微软雅黑</option>
                    <option value="KaiTi">楷体</option>
                    <option value="FangSong">仿宋</option>
                    <option value="Arial">Arial</option>
                  </select>
                  <!-- Add subscript and superscript buttons -->
                  <select
                    class="ql-color"
                    value="color"
                    title="字体颜色"
                  ></select>
                  <select
                    class="ql-background"
                    value="background"
                    title="背景颜色"
                  ></select>
                  <select class="ql-align" value="align" title="对齐"></select>
                  <button class="ql-clean" title="还原"></button>
                  <!-- You can also add your own -->
                </div>
              </quill-editor>
            </el-card>
          </div>
        </el-form-item>
        <el-form-item label="关键字" :label-width="formLabelWidth">
          <el-input v-model="xiugaiform.keywords" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="缩略图" :label-width="formLabelWidth">
          <el-upload
            action="http://121.42.230.80/api/visit/upload"
            list-type="picture-card"
            :headers="headers"
            :show-file-list="false"
            :on-success="chec"
            :auto-upload="true"
          >
            <img
              v-if="xiugaiform.thumb"
              :src="xiugaiform.thumb"
              class="avatar"
              style="width: 145px; height: 145px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="作者" :label-width="formLabelWidth">
          <el-input v-model="xiugaiform.author" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="介绍" :label-width="formLabelWidth">
          <el-input v-model="xiugaiform.desc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="xiug = false">取 消</el-button>
        <el-button type="primary" @click="xiugaiadd('xiugaiform')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { newlist, newadd } from "../api/news";
import http from "../utils/http";
import { Quill, quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
//引入font.css
import "../views/font.css";
// 自定义字体大小
let Size = Quill.import("attributors/style/size");
Size.whitelist = ["10px", "12px", "14px", "16px", "18px", "20px"];
Quill.register(Size, true);
// 自定义字体类型
var fonts = [
  "SimSun",
  "SimHei",
  "Microsoft-YaHei",
  "KaiTi",
  "FangSong",
  "Arial",
  "Times-New-Roman",
  "sans-serif",
  "宋体",
  "黑体",
];
var Font = Quill.import("formats/font");
Font.whitelist = fonts;
Quill.register(Font, true);

export default {
  data() {
    return {
      thumb: "",
      headers: { token: sessionStorage.getItem("token") },
      news_id: "",
      // 修改
      xiug: false,
      xiugaiform: {
        news_id: "",
        title: "",
        content: "",
        keywords: "",
        thumb: "",
        author: "",
        desc: "",
      },
      //搜索
      searcjed: "",
      // 表格
      tableData: [],
      // 总页数
      total: 0,
      // 页数
      params: {
        page: 1,
        pageSize: 5,
        idortitle: "",
      },

      // 复选框
      multipleSelection: [],
      // 弹框是否显示
      dialogFormVisible: false,
      form: {
        news_id: "",
        title: "",
        content: "",
        keywords: "",
        thumb: "",
        author: "",
        desc: "",
      },

      formLabelWidth: "120px",
      content: "<h2>I am Example</h2>",
      editorOption: {},
    };
  },

  mounted() {},

  methods: {
    imgError() {
      let img = event.srcElement;
      img.src = require("@/images/news.jpg");
      img.onerror = null; //防止闪图
    },
    // 添加
    att() {
      (this.form = {}), (this.xiugaiform.thumb = "");
      this.thumb = "";
      this.form.thumb = "";
      this.dialogFormVisible = true;
    },
    // 图片
    chec(response) {
      console.log(response);
      this.xiugaiform.thumb = response.data.src;
      this.thumb = response.data.src;
      this.form.thumb = response.data.src;
    },
    beforeAvatarUploads(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //  富文本编辑器
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    onEditorFocus(quill) {
      console.log("editor focus!", quill);
    },
    onEditorReady(quill) {
      console.log("editor ready!", quill);
    },
    onEditorChange({ quill, html, text }) {
      console.log("editor change!", quill, html, text);
      this.content = html;
    },
    // 修改
    async xiugai(row, news_id) {
      // console.log(111,row,news_id);

      this.id = news_id;

      // 深复制，避免列表对象和弹窗对象的数据同步改动。
      const _row = JSON.parse(JSON.stringify(row));
      // console.log(_row);
      this.xiug = true;
      this.xiugaiform = _row;
    },
    async xiugaiadd() {
      let res = await http.post("/api/visit/news/edit?id=" + this.id, {
        formdata: this.xiugaiform,
      });
      // console.log(res);
      if (res.code == "00000") {
        if (
          this.xiugaiform.title == "" ||
          this.xiugaiform.content == "" ||
          this.xiugaiform.keywords == "" ||
          this.xiugaiform.author == "" ||
          this.xiugaiform.thumb == ""
        ) {
          this.$message.error("内容不能为空");
          return;
        } else {
          this.xiug = false;
          this.getnewlist();
        }
      } else {
        this.$message.error("修改失败");
      }
    },
    // 详情
    xiangq(news_id) {
      this.$router.push({
        name: "Newsdetails",
        params: {
          id: news_id,
        },
      });
    },

    // 添加
    async add() {
      let res = await newadd(this.form);
      // console.log(res);
      if (res.code == "00000") {
        if (
          this.form.title == "" ||
          this.form.content == "" ||
          this.form.keywords == "" ||
          this.form.author == "" ||
          this.form.thumb == ""
        ) {
          this.$message.error("内容不能为空");
          return;
        } else {
          this.$message.success("添加成功");
          this.getnewlist();

          this.dialogFormVisible = false;
        }
      } else {
        this.$message.success("添加失败");
      }
    },
    // 复选框的数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除
    async deleteall() {
      let ids = this.multipleSelection.map((item) => item.news_id);
      // console.log(ids);
      const result = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          center: true,
        }
      ).catch((error) => {
        return error;
      });
      //点击确定是confirm
      if (result == "confirm") {
        let res = await http.get("/api/visit/news/del", { news_id: ids });
        console.log(res);
        if (res.code != "00000") {
          return this.$message.error("数据库异常！删除失败");
        }
        this.$message.success("删除成功");
        this.getnewlist();
      }
    },
    // 删除
    getdele(news_id) {
      // console.log(news_id);
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(async () => {
          let res = await http.get("/api/visit/news/del?news_id=" + news_id);
          // console.log(res);
          if (res.code == "00000") {
            this.getnewlist();
            this.$message.success("删除成功");
          } else {
            return this.$message.error("发生未知错误，删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 渲染列表
    async getnewlist() {
      let res = await newlist({
        page: this.params.page,
        pageSize: this.params.pageSize,
        idortitle: this.params.idortitle,
      });
      console.log(res);
      if (res.code == "00000") {
        this.tableData = res.data;
        this.total = res.total;
      }
    },
    // 分页
    handleSizeChange(val) {
      this.params.pageSize = val;
      this.getnewlist();
    },
    handleCurrentChange(val) {
      this.params.page = val;
      this.getnewlist();
    },
  },
  //富文本编辑器
  computed: {
    editor() {
      return this.$refs.myQuillEditor.quill;
    },
  },
  mounted() {
    // console.log("this is current quill instance object", this.editor);
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getnewlist();
  },
};
</script>
<style lang="less" scoped>
.block {
  text-align: center;
  margin-top: 10px;
}
/deep/.el-pagination .el-select .el-input .el-input__inner {
  padding-right: 25px;
  border-radius: 3px;
}
.el-input {
  width: 20%;
}
.el-dialog .el-input {
  width: 60%;
}
.nav {
  display: flex;
  align-items: center;
}
.btn {
  width: 69px;
  background-color: #85ce61;
  border: #85ce61 1px solid;
  border-radius: 3px;
  color: aliceblue;
  font-size: 16px;
  height: 38px;
  margin-left: 20px;
}
.banner {
  margin-top: 20px;
}
/deep/.cell {
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>